package com.learn.spring.test;

import com.learn.spring.User;
import com.learn.spring.autowire.Student;
import com.learn.spring.bean.CollectionModel;
import com.learn.spring.bean.LifeCycle;
import com.learn.spring.factory.TestFactoryBean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Case2 {

    /**
     * IOC操作Bean管理（FactoryBean)
     * 1、Spring 有两种类型 bean，一种普通 bean (我们自己写了后定义在xml配置里的)，另外一种工厂 bean (FactoryBean)
     * 普通bean: 在配置文件中定义 bean 类型就是返回类型，这里指的 <bean id="userDaoImpl" class="com.learn.spring.dao.UserDaoImpl"/>标签中的 class属性
     * 工厂bean: 在配置文件定义 bean 类型可以和返回类型不一样，其实就时一个实现了工厂接口的自定义类，但是spring指定了接口就是 FactoryBean
     */
    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans3.xml");
//        System.out.println(context.getBean("testFactoryBean", TestFactoryBean.class));
        // 工厂bean需要使用工厂接口实现的泛型作为接受类型
        System.out.println(context.getBean("testFactoryBean", String.class));
    }

    /**
     * 默认情况下spring创建的对象都是单例的，作用域时全局
     */
    @Test
    public void test1() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user1 = context.getBean("user", User.class);
        User user2 = context.getBean("user", User.class);
        System.out.println(user1);
        System.out.println(user2);
    }

    @Test
    public void test2() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans3.xml");
        User user1 = context.getBean("userSingleton", User.class);
        User user2 = context.getBean("userSingleton", User.class);
        System.out.println(user1);
        System.out.println(user2);
        User user3 = context.getBean("userPrototype", User.class);
        User user4 = context.getBean("userPrototype", User.class);
        System.out.println(user3);
        System.out.println(user4);
    }

    @Test
    public void test3() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans3.xml");
        LifeCycle lifeCycle = context.getBean("lifeCycle", LifeCycle.class);
        System.out.println("第四步 获取对象");
        System.out.println(lifeCycle);
        context.close();
    }

    @Test
    public void test4() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans3.xml");
        Student lifeCycle = context.getBean("student", Student.class);
        System.out.println(lifeCycle);
    }

    @Test
    public void test5() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans3.xml");
        Student student1 = context.getBean("student1", Student.class);
        System.out.println(student1);
    }

}
